import tkinter as tk
from tkinter import ttk, messagebox
import os
import sys
import subprocess

class MainApplication:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("翻译工具集")
        self.window.geometry("400x300")

        # 获取当前程序所在目录，兼容打包和未打包
        if getattr(sys, 'frozen', False):
            self.current_dir = os.path.dirname(sys.executable)
        else:
            self.current_dir = os.path.dirname(os.path.abspath(__file__))


        # 创建主框架
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 创建标题标签
        title_label = ttk.Label(
            main_frame,
            text="翻译工具集",
            font=("微软雅黑", 16, "bold")
        )
        title_label.pack(pady=20)

        # 创建PO文件翻译工具按钮
        po_translator_btn = ttk.Button(
            main_frame,
            text="PO文件翻译工具",
            command=self.open_po_translator,
            width=20
        )
        po_translator_btn.pack(pady=10)

        # 创建中文字符提取器按钮
        recipe_display_btn = ttk.Button(
            main_frame,
            text="中文字符提取器",
            command=self.open_recipe_display_collector,
            width=20
        )
        recipe_display_btn.pack(pady=10)

        # 创建多项合并到PO文件按钮
        merge_to_po_btn = ttk.Button(
            main_frame,
            text="多行项合并到PO文件",
            command=self.open_merge_to_po,
            width=20
        )
        merge_to_po_btn.pack(pady=10)


    def open_po_translator(self):
        """打开PO文件翻译工具"""
        self.run_tool('po_translator')

    def open_recipe_display_collector(self):
        """打开中文字符提取器"""
        self.run_tool('chinese_extractor')

    def open_merge_to_po(self):
        """打开多项合并到PO文件工具"""
        self.run_tool('merge_to_po')

    def run_tool(self, tool_name):
        """
        根据环境自动运行 exe 或 py 工具
        :param tool_name: 不带扩展名的工具名，如 'po_translator'
        """
        exe_path = os.path.join(self.current_dir, f"{tool_name}.exe")
        py_path = os.path.join(self.current_dir, f"{tool_name}.py")
        try:
            if os.path.exists(exe_path):
                subprocess.Popen([exe_path], cwd=self.current_dir)
            elif os.path.exists(py_path):
                python_exe = sys.executable
                subprocess.Popen([python_exe, py_path], cwd=self.current_dir)
            else:
                messagebox.showerror("错误", f"找不到{tool_name}工具")
                # messagebox.showerror("错误", f"找不到{exe_path}工具")
                # messagebox.showerror("错误", f"找不到{py_path}工具")
        except Exception as e:
            messagebox.showerror("错误", f"启动{tool_name}工具时出错：{str(e)}")

    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    app = MainApplication()
    app.run()